package com.liyunc.demo.service.base;
/**
 * Copyright (c) 2018-2022 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.liyunc.demo.model.entity.UserInfo;
import com.liyunc.demo.model.repository.FileInfoRepository;
import com.liyunc.demo.model.repository.PermissionInfoRepository;
import com.liyunc.demo.model.repository.ProjectInfoRepository;
import com.liyunc.demo.model.repository.RoleInfoRepository;
import com.liyunc.demo.model.repository.UserInfoRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.util.List;

/**
 * @author
 * @version 1.0
 * @file
 * @brief
 * @details
 * @date 2022-02-18
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-02-18                       Created
 */
@Service
public class BaseService {

    @Autowired
    protected ProjectInfoRepository projectInfoRepository;

    @Autowired
    protected UserInfoRepository userInfoRepository;

    @Autowired
    protected RoleInfoRepository roleInfoRepository;

    @Autowired
    protected FileInfoRepository fileInfoRepository;

    @Autowired
    protected PermissionInfoRepository permissionInfoRepository;

    /**
     * 获取当前用户.
     */
    private String currentUsername() {
        Object principal = SecurityContextHolder
            .getContext()
            .getAuthentication()
            .getPrincipal();

        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }

        if (principal instanceof Principal) {
            return ((Principal) principal).getName();
        }
        return String.valueOf(principal);
    }

    /**
     * 获取当前用户.
     */
    public UserInfo currentUser() {
        return userInfoRepository.findByUsername(currentUsername());
    }

    /**
     * 验证当前用户是否有此项目权限.
     */
    public boolean authProject(long projectId) {
        Long userId = userInfoRepository.findByUsername(currentUsername()).getId();
        if (isAdmin(userId)) {
            return true;
        }
        List<Long> list = roleInfoRepository.findProjectIdByUserId(userId);
        return list.stream().anyMatch(item -> item == projectId);
    }

    private boolean isAdmin(Long userId) {
        if (userInfoRepository.findById(userId).isPresent()) {
            return StringUtils
                .equals(userInfoRepository.findById(userId).get().getUsername(), "admin");
        }
        return false;
    }
}
